﻿//using System;
//using System.Threading;
//using System.Threading.Tasks;

//namespace MangosRestarter
//{
//    /// <summary>
//    /// MySQL监控器
//    /// </summary>
//    internal static class MySqlMonitor
//    {
//        private static CancellationTokenSource monitoringCts;
//        private static bool isMonitoring = false;
//        private static Action<string> logCallback;
//        private static Action updateStatusCallback;

//        /// <summary>
//        /// 启动MySQL监控
//        /// </summary>
//        public static void StartMonitoring(Action<string> log, Action updateStatus)
//        {
//            if (isMonitoring) return;

//            logCallback = log;
//            updateStatusCallback = updateStatus;
//            monitoringCts = new CancellationTokenSource();
//            isMonitoring = true;

//            Task.Run(() => MonitorWorker(monitoringCts.Token));
//            log("MySQL监控已启动");
//        }

//        /// <summary>
//        /// 停止MySQL监控
//        /// </summary>
//        public static void StopMonitoring()
//        {
//            monitoringCts?.Cancel();
//            isMonitoring = false;
//            logCallback?.Invoke("MySQL监控已停止");
//        }

//        /// <summary>
//        /// 监控工作线程
//        /// </summary>
//        private static async Task MonitorWorker(CancellationToken token)
//        {
//            while (!token.IsCancellationRequested)
//            {
//                try
//                {
//                    bool isRunning = MySqlChecker.IsRunning();
//                    updateStatusCallback?.Invoke();

//                    if (!isRunning && ConfigHelper.StartMySql)
//                    {
//                        logCallback?.Invoke("MySQL未运行，正在重新启动...");
//                        if (MySqlStarter.TryStartWithVisibleConsole(out string error))
//                        {
//                            logCallback?.Invoke("MySQL重新启动成功");
//                        }
//                        else
//                        {
//                            logCallback?.Invoke($"[ERROR] MySQL重新启动失败: {error}");
//                        }
//                    }

//                    await Task.Delay(5000, token);
//                }
//                catch (TaskCanceledException)
//                {
//                    break;
//                }
//                catch (Exception ex)
//                {
//                    logCallback?.Invoke($"[ERROR] MySQL监控异常: {ex.Message}");
//                    await Task.Delay(5000, token);
//                }
//            }
//        }
//    }
//}

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace MangosRestarter
{
    /// <summary>
    /// MySQL监控器
    /// </summary>
    internal static class MySqlMonitor
    {
        private static CancellationTokenSource monitoringCts;
        private static bool isMonitoring = false;
        private static Action<string> logCallback;
        private static Action updateStatusCallback;
        private static DateTime lastResponseTime;
        private const int HangTimeoutMs = 60000; // 60秒无响应认为卡死

        /// <summary>
        /// 启动MySQL监控
        /// </summary>
        public static void StartMonitoring(Action<string> log, Action updateStatus)
        {
            if (isMonitoring) return;

            logCallback = log;
            updateStatusCallback = updateStatus;
            monitoringCts = new CancellationTokenSource();
            isMonitoring = true;
            lastResponseTime = DateTime.Now;

            Task.Run(() => MonitorWorker(monitoringCts.Token));
            log("MySQL监控已启动");
        }

        /// <summary>
        /// 停止MySQL监控
        /// </summary>
        public static void StopMonitoring()
        {
            monitoringCts?.Cancel();
            isMonitoring = false;
            logCallback?.Invoke("MySQL监控已停止");
        }

        /// <summary>
        /// 检查MySQL进程是否卡死
        /// </summary>
        private static bool IsMySqlHanged()
        {
            try
            {
                var processes = Process.GetProcessesByName("mysqld");
                foreach (var process in processes)
                {
                    if (!process.HasExited && process.Responding == false)
                    {
                        return true;
                    }
                }

                // 检查响应超时
                return (DateTime.Now - lastResponseTime).TotalMilliseconds > HangTimeoutMs;
            }
            catch (Exception ex)
            {
                logCallback?.Invoke($"[ERROR] 检查MySQL状态失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 强制终止MySQL进程
        /// </summary>
        private static void ForceKillMySql()
        {
            try
            {
                var processes = Process.GetProcessesByName("mysqld");
                foreach (var process in processes)
                {
                    try
                    {
                        if (!process.HasExited)
                        {
                            process.Kill();
                            process.WaitForExit(5000);
                            logCallback?.Invoke($"已强制终止卡死的MySQL进程: {process.Id}");
                        }
                    }
                    catch (Exception ex)
                    {
                        logCallback?.Invoke($"[ERROR] 终止MySQL进程失败 {process.Id}: {ex.Message}");
                    }
                }

                // 同时终止可能的mysqld-nt进程
                processes = Process.GetProcessesByName("mysqld-nt");
                foreach (var process in processes)
                {
                    try
                    {
                        if (!process.HasExited)
                        {
                            process.Kill();
                            process.WaitForExit(5000);
                        }
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                logCallback?.Invoke($"[ERROR] 查找MySQL进程失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 监控工作线程
        /// </summary>
        private static async Task MonitorWorker(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    // 检查MySQL是否在运行
                    bool isRunning = MySqlChecker.IsRunning();

                    // 更新状态显示
                    updateStatusCallback?.Invoke();

                    if (isRunning)
                    {
                        // 检查MySQL是否卡死
                        if (IsMySqlHanged())
                        {
                            logCallback?.Invoke("[ERROR] MySQL检测到卡死，正在重启...");
                            ForceKillMySql();
                            await Task.Delay(5000, token); // 等待5秒让进程完全退出

                            // 重新启动MySQL
                            if (MySqlStarter.TryStartWithVisibleConsole(out string error))
                            {
                                logCallback?.Invoke("MySQL重启成功");
                                lastResponseTime = DateTime.Now;
                            }
                            else
                            {
                                logCallback?.Invoke($"[ERROR] MySQL重启失败: {error}");
                            }
                        }
                        else
                        {
                            lastResponseTime = DateTime.Now; // 更新响应时间
                        }
                    }
                    else if (ConfigHelper.StartMySql)
                    {
                        logCallback?.Invoke("MySQL未运行，正在重新启动...");
                        if (MySqlStarter.TryStartWithVisibleConsole(out string error))
                        {
                            logCallback?.Invoke("MySQL重新启动成功");
                            lastResponseTime = DateTime.Now;
                        }
                        else
                        {
                            logCallback?.Invoke($"[ERROR] MySQL重新启动失败: {error}");
                        }
                    }

                    // 每5秒检查一次
                    await Task.Delay(5000, token);
                }
                catch (TaskCanceledException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    logCallback?.Invoke($"[ERROR] MySQL监控异常: {ex.Message}");
                    await Task.Delay(5000, token);
                }
            }
        }
    }
}